package org.fb.controller;

import com.alibaba.fastjson.JSONObject;
import org.fb.bean.UserServiceBeanDefinition;
import org.fb.bean.UserServiceBeanFactory;
import org.fb.handler.ServerBalanceHandler;
import org.fb.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author fanbo@imoran.net
 * @date 2021/2/23 11:20
 */

@RestController
@RequestMapping("/sayhi")
public class SayHiController {

    @Autowired
    private ServerBalanceHandler serverBalanceHandler;

    /**
     * 测试向服务器发送数据
     *
     * @param msg
     * @return
     */
    @GetMapping("/sendData")
    public String sendData(@RequestParam("msg") String msg) {
        System.out.println("收到请求query: " + msg);
        UserServiceBeanDefinition userServiceBeanDefinition = UserServiceBeanFactory.beanList.get(0);
        System.out.println("请求服务节点： " + userServiceBeanDefinition.getServerName());
        IUserService userService = userServiceBeanDefinition.getUserService();
        return JSONObject.toJSONString(userService.sayHello(msg));
    }

    /**
     * 测试向服务器发送数据(添加负载均衡策略)
     *
     * @param msg
     * @return
     */
    @GetMapping("/sendDataBalance")
    public String sendDataBalance(@RequestParam("msg") String msg) {
        // 负载均衡获取服务端
        UserServiceBeanDefinition userServiceBeanDefinition = serverBalanceHandler.serverBalance();
        IUserService userService = userServiceBeanDefinition.getUserService();

        long startTime = System.currentTimeMillis();
        String result = JSONObject.toJSONString(userService.sayHello(msg));
        long endTime = System.currentTimeMillis();

        // 记录服务器响应耗时
        long time = endTime - startTime;
        String serverName = userServiceBeanDefinition.getServerName();
        System.out.println("接受请求的服务：" + serverName);

        ServerBalanceHandler.serverResponseTimeMap.put(serverName, time);
        return result;
    }
}
